/* eslint-disable @typescript-eslint/no-explicit-any */
import { useChatStore } from '@/store/useChatStore'
import { useLoginUserStore } from '@/store/useLoginUserStore'

const chatStore = useChatStore()
const loginUserStore = useLoginUserStore()

// 消息类型定义
export interface WsMessage {
    event: string
    eventContent: unknown
}


const receiveWsMessage = (wsMessage: WsMessage) => {
    console.log('收到信息', wsMessage)
    const { event, eventContent } = wsMessage
    if (event === 'receiveMessage') {
        const { srcUid, targetUid } = eventContent as any
        if (targetUid !== loginUserStore.uid) {
            return
        }
        if (!chatStore.chatMap.has(srcUid)) {
            chatStore.chatMap.set(srcUid, [])
        }
        chatStore.chatMap.get(srcUid).push(eventContent)
    }
}



let client: WebSocket | null = null
let reconnectTimer: unknown = 0
const reconnectDelay = 5000
const url: string = ((window as any).APP_CONFIG?.WSS_BASE_URL || '')



const openHandle = () => {
    console.log('WebSocket 连接成功')
    clearReconnect()
}
const closeHandle = (event: any) => {
    console.log(`WebSocket 连接关闭，代码：${event.code}，原因：${event.reason}`)
    if (event.code !== 1000) { // 非主动关闭则重连
        startReconnect()
    }
}
const messageHandle = (event: any) => {
    try {
        const wsMessage = JSON.parse(event.data.toString()) as WsMessage
        receiveWsMessage(wsMessage)
    } catch (error) {
        console.error('解析消息失败：', error)
    }
}
const errorHandle = (event: any) => {
    console.error('WebSocket 错误：', event)
}

const connect = () => {
    const token = localStorage.getItem('token')?.split(' ')[1]
    const urlWithToken = new URL(url)
    urlWithToken.searchParams.append('token', token as string)
    console.log('发起连接...')
    // 关闭已有连接
    if (client) {
        client.close(1000, '初始化新连接，主动关闭旧连接')
    }

    // 创建连接
    client = new WebSocket(urlWithToken.toString())
    client.addEventListener('open', openHandle)
    client.addEventListener('close', closeHandle)
    client.addEventListener('message', messageHandle)
    client.addEventListener('error', errorHandle)


}

const sendMessage = (data: Omit<WsMessage, 'time'>): boolean => {
    if (client && client.readyState === WebSocket.OPEN) {
        client.send(JSON.stringify(data))
        return true
    }
    console.warn('WebSocket 未连接，无法发送消息')
    return false
}

const startReconnect = (): void => {
    clearReconnect()
    reconnectTimer = setInterval(() => {
        console.log('尝试重连 WebSocket...')
        connect()
    }, reconnectDelay)
}

const clearReconnect = (): void => {
    if (reconnectTimer) {
        clearInterval(reconnectTimer as any)
        reconnectTimer = null
    }
}

// 主动关闭连接
const close = (): void => {
    if (client) {
        client.close(1000, '主动关闭连接')
        clearReconnect()
    }
}


// 导出单例实例
export default {
    connect,
    close,
    sendMessage
}
